#include "lc.hh"

// help page
void
print_help()
{
  cerr << endl;
  cerr << "<usage>" << endl;
  cerr << " <bin> infile outfile K maxiter tol nrepeat" << endl;
  cerr << endl;
}

// main routine
int
main(const int argc, const char* argv[])
{
  string infile;
  string outfile;
  int K;
  int max_iter;
  double tol;
  int nrepeat;

  if( argc < 7 )
    {
      print_help();
      exit(1);
    }

  try
  {
      infile = argv[1];
      outfile = argv[2];
      K = boost::lexical_cast<int>( argv[3] );
      max_iter = boost::lexical_cast<int>( argv[4] );
      tol = boost::lexical_cast<double>( argv[5] );
      nrepeat = boost::lexical_cast<int>( argv[6] );
  }
  catch(boost::bad_lexical_cast &)
  {
      cerr << "check out input arguments!" << endl;
      print_help();
      exit(1);
  }

  mat_pt Wpt = read_pairs( infile.c_str(), true );
  const mat_t& W = *(Wpt.get());
  cerr << " -- read data" << endl;

  mat_pt bestMatPtr;
  double bestScore;
  random_index_t rIdx(K);

  for(int r=1; r<=nrepeat; ++r)
    {
      cerr << " -- r = " << r << " / " << nrepeat << endl;
      mat_pt degMatPtr = fit_model( W, K, max_iter, tol, rIdx );
      double llik = log_lik( W, *(degMatPtr.get()) );
      cerr << " -- score = " << llik << endl;
      if( r == 1 || llik > bestScore )
        {
          bestScore = llik;
          bestMatPtr = degMatPtr;
        }
    }

  // output
  cerr << " -- output" << endl;
  write_propensity( *(bestMatPtr.get()), outfile.c_str() );

  // output best score
  ofstream LOG( (outfile+".log").c_str() );
  LOG << bestScore << endl;
  LOG.close();


  return 0;
}
